# -*- coding=UTF-8 -*-

import wx
import wx.xrc
import logging
import pyperclip

logging.basicConfig(filename="./log/gui.log", filemode='w',
                    format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.DEBUG)

from bridge.readconf import ReadConf


class ChangePanel(wx.Panel):

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 300), style=wx.TAB_TRAVERSAL,
                 name=wx.EmptyString):
        self.cf = ReadConf()
        wx.Panel.__init__(self, parent, id=id, pos=pos, size=size, style=style, name=name)

        bSizer1 = wx.BoxSizer(wx.VERTICAL)

        gbSizer1 = wx.GridBagSizer(0, 0)
        gbSizer1.SetFlexibleDirection(wx.BOTH)
        gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.api_staticText = wx.StaticText(self, wx.ID_ANY, u"api来源：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.api_staticText.Wrap(-1)

        gbSizer1.Add(self.api_staticText, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

        api_comboBoxChoices = [u"百度Ai"]
        self.api_comboBox = wx.ComboBox(self, wx.ID_ANY, u"百度Ai", wx.DefaultPosition, wx.Size(120, -1),
                                        api_comboBoxChoices, 0)
        self.api_comboBox.SetSelection(0)
        gbSizer1.Add(self.api_comboBox, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.appid_staticText = wx.StaticText(self, wx.ID_ANY, u"APP_ID:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.appid_staticText.Wrap(-1)

        gbSizer1.Add(self.appid_staticText, wx.GBPosition(0, 2), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.chapi = 'baidu' if self.api_comboBox.GetSelection() == 0 else ''  # 如果选择0，则返回baidu,非0，则返回空
        self.confdict = dict(self.cf.get_section_dict(self.chapi))

        appid = self.confdict['app_id']
        self.appid_textCtrl = wx.TextCtrl(self, wx.ID_ANY, appid, wx.DefaultPosition, wx.Size(130, -1), 0)
        self.appid_textCtrl.Enable(False)
        gbSizer1.Add(self.appid_textCtrl, wx.GBPosition(0, 3), wx.GBSpan(1, 2), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.my_staticText = wx.StaticText(self, wx.ID_ANY, u"密钥：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.my_staticText.Wrap(-1)

        gbSizer1.Add(self.my_staticText, wx.GBPosition(0, 5), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        secretkey = self.confdict['secret_key']
        self.my_textCtrl = wx.TextCtrl(self, wx.ID_ANY, secretkey, wx.DefaultPosition, wx.Size(180, -1),
                                       wx.TE_PASSWORD)
        self.my_textCtrl.Enable(False)

        gbSizer1.Add(self.my_textCtrl, wx.GBPosition(0, 6), wx.GBSpan(1, 2), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        bSizer1.Add(gbSizer1, 0, 0, 5)

        self.m_staticline = wx.StaticLine(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL)
        bSizer1.Add(self.m_staticline, 0, wx.EXPAND | wx.ALL, 5)

        bSizer2 = wx.BoxSizer(wx.HORIZONTAL)

        self.en_textCtrl = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
                                       wx.TE_MULTILINE)
        bSizer2.Add(self.en_textCtrl, 1, wx.ALL | wx.EXPAND, 5)

        self.ch_button = wx.Button(self, wx.ID_ANY, u"En>> 翻译 >>Ch", wx.DefaultPosition, wx.DefaultSize, 0)

        self.ch_button.SetDefault()
        bSizer2.Add(self.ch_button, 0, wx.ALL | wx.ALIGN_TOP, 5)

        self.ch_textCtrl = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
                                       wx.TE_MULTILINE)
        self.ch_textCtrl.Enable(False)

        bSizer2.Add(self.ch_textCtrl, 1, wx.ALL | wx.EXPAND, 5)

        bSizer1.Add(bSizer2, 1, wx.EXPAND, 5)

        self.SetSizer(bSizer1)
        self.Layout()

        # Connect Events
        self.ch_button.Bind(wx.EVT_BUTTON, self.ai_changes)
        self.api_comboBox.Bind(wx.EVT_CHOICE, self.change_value)
        # self.en_textCtrl.Bind(wx.EVT_END_PROCESS, self.s_change)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def ai_changes(self, event):
        """
        点击 翻译 按钮事件
        :param event:
        :return:
        """
        event.GetEventObject().Disable()
        try:
            vervalue = self._verify_values()
            if vervalue[0]:
                self.chtext = self._en_changeto_zh()
                self.ch_textCtrl.Update()
                self.ch_textCtrl.SetValue(self.chtext)
                logging.info("====翻译的英文为：{}".format(self.entext))
                logging.info("====翻译结果为：{}".format(self.chtext))
            else:
                wx.MessageBox("请检查{}".format(vervalue[1]))
        except BaseException as e:
            wx.MessageBox(e)
        finally:
            event.GetEventObject().Enable()

    # 还没有写完
    def change_value(self, event):
        """
        重新获取接口值
        :param event:
        :return:
        """
        event.GetEventObject.Disable()
        try:
            choice = 'youdao' if self.api_comboBox.GetSelection() == 1 else 'baidu'
            api_info = dict(self.cf.get_section_dict(choice))
            self.appid_textCtrl.SetValue(api_info['app_id'])
            self.my_textCtrl.SetValue(api_info['secret_key'])
        except BaseException as e:
            wx.MessageBox(e)
        finally:
            event.GetEventObject.Enable()

    def _en_changeto_zh(self):
        """
        英文 翻译成 中文
        :return:
        """
        try:
            self.entext = self.en_textCtrl.GetValue()
            from bridge.change import EnChange
            ch = EnChange(self.confdict['api_url'], self.confdict['app_id'], self.confdict['secret_key'], self.entext)
            chtext = ch.request_api()
            return chtext
        except BaseException as e:
            logging.error(e)
            return e

    def _verify_values(self):
        """
        验证接口必要信息是否齐全
        :return:
        """
        try:
            values = {"api_url": self.confdict['api_url'],
                      "app_id": self.confdict['app_id'],
                      "secret_key": self.confdict['secret_key'],
                      "entext": self.en_textCtrl.GetValue()}
            for k, v in values.items():
                if v.strip():
                    pass
                else:
                    return False, k
            else:
                return True, True
        except BaseException as e:
            logging.error(e)
            return False, e

    # def __get__copypane(self):
    #
    #
    #         self.en_textCtrl.SetValue(pyperclip.paste)